#### Figure 4: Norm Violations and Violence Support (Partisan Perceptions) ####

# Libraries
# library(here)
# library(rio)
# library(tidyverse)
# library(ggthemes)
# library(srvyr)

# data_pnas = import(here("Data","data_pnas.rds"))
# source(here("Code","Functions","funcs_theme.R"))

violence_perc = paste0("violence",c(3,6),"_perception")
norm_perc = paste0("norm_",c("judges","polling","censorship","loyalty"),"_perception")

cs_perception = data_pnas |> 
  filter(pid %in% c("Democrat","Republican")) |> # Just D/R
  select(pid, all_of(c(violence_perc, norm_perc)),uid, weight) |> 
  pivot_longer(-c("pid","uid","weight"), names_to = "var", values_to = "val") |> 
  mutate(val = val/100) |> 
  as_survey_design(ids = uid, weights = weight) |> 
  group_by(pid, var) |> 
  summarise(val_sum = survey_mean(val, na.rm = T, vartype = "ci")) |> 
  ungroup() |> 
  mutate(var_typ = ifelse(str_detect(var,"norm"), "Democratic Norms", "Violence"),
         var = recode_factor(var,
                             norm_polling_perception = "Reduce outparty polling stations",
                             norm_loyalty_perception = "More loyal to party than Constitution\nin contested elections",
                             norm_judges_perception = "Ignore outparty court decisions",
                             norm_executive_perception = "President should circumvent Congress",
                             norm_censorship_perception = "Censor partisan media",
                             violence6_perception = "Murder",
                             violence3_perception = "Assault")
  )

fig_4 = cs_perception |> 
  ggplot(aes(x = val_sum,
             y = tidytext::reorder_within(var, val_sum, var_typ), 
             group = pid,
             label = paste0(round(val_sum,3)*100,"%"))) +
  geom_pointrange(aes(xmin = val_sum_low,
                      xmax = val_sum_upp,
                      color = pid),
                  position = position_dodge(.5), size=.4) +
  geom_text(aes(x = val_sum + .13),
            position = position_dodge(.95), size=3) +
  facet_wrap(~ var_typ, scales = "free_y", ncol=1) +
  force_panelsizes(rows = c( 1,.45)) +
  scale_color_manual(name = "Party of the respondent",
                     values = c("blue","red"),
                     guide = guide_legend(title.position = 'top')) +
  scale_x_continuous(labels = scales::percent,
                     limits = c(0,1)) +
  tidytext::scale_y_reordered() +
  labs(x = "Percent Perceived Support in Out-Party",
       y = NULL) +
  theme_prl(base_family = "Helvetica")

print(fig_4)

ggsave(here("Plots","Main","figure_4.pdf"),
       fig_4,
       units = "in",
       width = 5, height = 4,
       dpi = 600)